package com.andro.inje.chansung.bus;

import java.io.IOException;
import java.util.Calendar;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.andro.inje.chansung.ConstantName;
import com.andro.inje.chansung.DB;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;

public class BusDetailUpdateThread extends Thread {
	private Activity activity;
	private Handler handler;
	private String name;
	private Calendar calendar;
	private String url;
	
	public BusDetailUpdateThread(Activity activity, Handler handler, String url, String name, Calendar calendar) {
		this.activity = activity;
		this.handler = handler;
		this.name = name;
		this.calendar = calendar;
		this.url = url;
	}
	
	public void run() {
		try {
			Document doc = Jsoup.connect(url).data("name", name).get();
			Element coming = doc.select("coming").get(0);
			Element leaving = doc.select("leaving").get(0);
			
			Elements comingBusList = coming.select("time");
			
			SQLiteDatabase db = activity.openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_WRITEABLE, null);
			for( Element element : comingBusList ) {
				String time = element.attr("value");
				String number = element.select("number").get(0).text();
//				String attention = element.select("attention").get(0).text();
				String description = element.select("description").get(0).text();
				
				BusDetail bus = new BusDetail(Integer.parseInt(number), name, time, "", description, true);
				DB.insertDetailDataIntoBusTable(db, bus);
			}
			
			Elements leavingBusList = leaving.select("time");
			for( Element element : leavingBusList ) {
				String time = element.attr("value");
				String number = element.select("number").get(0).text();
//				String attention = element.select("attention").get(0).text();
				String description = element.select("description").get(0).text();
				
				BusDetail bus = new BusDetail(Integer.parseInt(number), name, time, "", description, false);
				DB.insertDetailDataIntoBusTable(db, bus);
			}
			
			db.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		handler.sendEmptyMessage(0); 
	}
}
